from django.shortcuts import render,HttpResponse,HttpResponseRedirect
import random
from django.views.decorators.cache import cache_page
from django.template import loader
# Create your views here.
from django.views.generic.edit import BaseFormView,FormView
from myapp.forms import UploadForm
from myapp.models import UploadImgModel
from django.conf import settings
import os
from rest_framework.decorators import detail_route,list_route
from django.core.files.base import ContentFile
def index(request):

    context = {'ip': request.META['REMOTE_ADDR'],
               'dfs': request.META['HTTP_USER_AGENT'][13:27],
               'we': request.META['HTTP_USER_AGENT'][75:95],
               }
    return render(request, "blog.html", context)

# 1. 定义路由，分表使用静态、动态、传递更多参数
# 2. 定义快捷方法。使用快捷方法 渲染模板
# 3. 使用视图装饰器，缓存视图的结果（视图应该返回随机）

def run(request,name,context=None):
    template_name=name
    template=loader.render_to_string(template_name,context)
    return HttpResponse(template,context)
@cache_page(60*3)
def my_add(request,num1,num2,path):
    a=random.randint(0,50)
    context={
        'a':num1,
        'b':num2,
        'c':num1+num2,
        'img':path,
        'number':a
    }
    return run(request,'new_page.html',context)

# 1. 使用django内置视图，实现model查询和显示，包括详情页面 和 列表页面


from django.views.generic import DetailView,ListView,View
from .models import Course
from django.shortcuts import get_object_or_404


class CourseDetailView(DetailView):
    model =Course

class CourseListView(ListView):
    model = Course


# 2. 通过重写父类属性，只允许HTTP post 方法 ，来请求详情页 和列表页
def course_detail(request):
    a=request.POST.get('id')
    obj=get_object_or_404(Course,id=a)
    return render(request,'myapp/course_detail.html',{'object':obj})

class MyDetailView(View):
    http_method_names =['post',]
    def post(self, request):
       return HttpResponse(course_detail(request))

def course_list(request):
    a=Course.objects.all()
    return render(request,'myapp/course_list.html',{'object_list':a})

class MyListView(View):
    http_method_names =['post',]
    def post(self, request):
       return HttpResponse(course_list(request))

# 通过模型表单实现对数据的增删查改

# from myapp import models
#
# def add(request):
#     if request.method=="POST":
#         a_title=request.POST['a_title']
#         a_credit=request.POST['a_credit']
#         models.Course.objects.create(title=a_title,credit=a_credit)
#     user_list=models.Course.objects.all()
#     return render(request,'add.html',{'user_list':user_list})
#
# def delete(request):
#     if request.method=="POST":
#         a_title=request.POST['a_title']
#         models.Course.objects.filter(title=a_title).delete()
#     user_list = models.Course.objects.all()
#     return render(request, 'delete.html', {'user_list': user_list})
#
# def update(request):
#     if request.method=="POST":
#         a_title=request.POST['a_title']
#         a_credit=request.POST['a_credit']
#         models.Course.objects.filter(title=a_title).update(credit=a_credit)
#     user_list = models.Course.objects.all()
#     return render(request, 'update.html', {'user_list': user_list})


# 通过模型表单实现对数据的增删查改
from django.views.generic import CreateView,DeleteView,UpdateView
from myapp.forms import CourseForm
class Create(CreateView):
    model = Course
    form_class = CourseForm
    success_url = 'http://127.0.0.1:8000/admin/myapp/course/'

class Delete(DeleteView):
    model = Course
    form_class = CourseForm
    success_url = 'http://127.0.0.1:8000/admin/myapp/course/'

class Update(UpdateView):
    model = Course
    form_class = CourseForm
    success_url = 'http://127.0.0.1:8000/admin/myapp/course/'

class UploadView(FormView):
    form_class =UploadForm
    template_name ='upload.html'

    def form_valid(self, form):
        file=form.cleaned_data['head_img']
        file_path=os.path.join(settings.MEDIA_ROOT,file.name)

        with open(file_path,'wb+') as f:
            for block in file.chunks():
                f.write(block)
        request=self.request
        file_url=f"{request.scheme}://{request.get_host()}{settings.MEDIA_URL}{file.name}"
        return HttpResponseRedirect(file_url)


from myapp.forms import UploaderImageForm


def uploadImg(request):
    if request.method == 'POST':
        img = UploadImgModel(img_url=request.FILES.get('imgs'))
        img.save()
        # return HttpResponse('上传成功')
    return render(request, 'img.html')

from rest_framework.viewsets import ModelViewSet
from myapp.serializers import CourseSerializer
from rest_framework import permissions,pagination

from django_filters.rest_framework.backends import DjangoFilterBackend

class CourseViewSet(ModelViewSet):
    """Course课程名的接口"""
    queryset = Course.objects.all()
    serializer_class =CourseSerializer
    permission_classes = (permissions.IsAuthenticated,)
    pagination_class=pagination.LimitOffsetPagination
    # filter_backends =(DjangoFilterBackend,)
    # filter_fields=('type',)

















